package casa.depesos.app.com.http.req;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import casa.depesos.app.com.App;
import casa.depesos.app.com.http.HttpReq;
import casa.depesos.app.com.http.Req;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.WhiteDataBean;
import casa.depesos.app.com.http.data.WhiteData;
import casa.depesos.app.com.http.parser.WhiteDataParser;
import casa.depesos.app.com.utils.Constant;
import okhttp3.FormBody;

public class GetWhiteReq implements HttpReq<WhiteDataBean> {

    public GetWhiteReq() {
        System.currentTimeMillis();
    }

    @Override
    public void req(ReqCallback<WhiteDataBean> callback) {//  queryData
        if (Constant.data != null) {
            callback.callback(true, new WhiteDataBean(Constant.data));
            return;
        }
//        if (BuildConfig.DEBUG) {
//            WhiteDataBean bean = new WhiteDataBean(getData());
//            Constant.data = bean.data;
//            callback.callback(true, bean);
//            return;
//        }
        FormBody.Builder builder = new FormBody.Builder();
        Req.post("/app/system/fetchDataSummary", getParam(), getHeader(), builder.build(), new WhiteDataParser(), callback, this);
    }

    public WhiteDataBean req() {
        if (Constant.data != null) {
            return new WhiteDataBean(Constant.data);
        }
//        if (BuildConfig.DEBUG) {
//            WhiteDataBean bean = new WhiteDataBean(getData());
//            Constant.data = bean.data;
//            return bean;
//        }
        FormBody.Builder builder = new FormBody.Builder();
        try {
            return Req.post("/app/system/fetchDataSummary", getParam(), getHeader(), builder.build(), new WhiteDataParser(), this);
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
    }

    private WhiteData getData() {
        try {
            InputStream inputStream = App.getApp().getAssets().open("json");
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            String fileContent = stringBuilder.toString();
            // 关闭InputStream
            inputStream.close();
            // 将json字符串转换成List
            return new Gson().fromJson(fileContent, WhiteData.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean pass() {
        return true;
    }
}
